const Koa = require('koa')
const path = require('path')
const fs = require('fs')

const app = new Koa()

// 总耗时中间件
app.use(async (context, next) => {
  let startTime = Date.now()
  await next()
  console.log(context.request.url + ' ' + (Date.now() - startTime) / 1000 + '秒')
})

// 响应头中间件
app.use(async (context, next) => {
  context.set('Content-Type', 'application/json; charset=UTF-8')
  context.set("Access-Control-Allow-Origin","*")
  context.set("Access-Control-Allow-Methods" , "OPTIONS,GET,PUT, POST, DELETE")
  await next()
})

// 响应体中间件
app.use(async (context, next) => {
  let url = context.request.url.replace('/api/', '')
  let dir = path.join(__dirname, 'data', url + '.json')
  context.response.body = await new Promise(resolve => {
    fs.readFile(dir, (err, data) => {
      if (err) return resolve('{"err": true}')
      resolve(data)
    })
  })
  await next()
})

app.listen(3000)
